"""
file: loginPage.py
Author: 城下秋草
Desc: 登录页面对象
"""
import re

from playwright.sync_api import Page, expect

from pom.pages.basePage import BasePage
from pom.util.logger import logger

class LoginPage(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.page = page
        self.user_box = self.get_element("username","test-id")
        self.pass_box = self.get_element("password","id")
        self.login_btn = self.get_element("login-button","test-id")
        self.error_txt = self.get_element("error","test-id")

    def login(self,username,password):
        self.user_box.fill(username)
        self.pass_box.fill(password)
        self.login_btn.click()

    def visit(self,url):
        self.page.goto(url)
        expect(self.page).to_have_url(re.compile("saucedemo"))

    @property
    def error_msg(self):
        if self.error_txt.is_visible():
            return self.error_txt.text_content()
        else:
            return ""

    def 输入用户名(self,username):
        logger.info("输入用户名")
        self.user_box.fill(username)

    def 输入密码(self,password):
        logger.info("输入密码")
        self.pass_box.fill(password)

    def 点击登录(self):
        logger.info("点击登录")
        self.login_btn.click()

    def 验证登录成功(self):
        logger.info("验证登录成功")
        assert self.get_element("title","test-id").is_visible()
        assert self.get_element("title","test-id").text_content() == "Products"

    def 验证错误信息(self, msg):
        logger.info("验证错误信息")
        assert msg in self.error_msg